import React from 'react';
import PageLayout from 'jjb-react-admin-component-new/PageLayout';
import SearchForm from '@cqsjjb/jjb-react-admin-component/SearchForm';
import ControlWrapper from 'jjb-react-admin-component-new/ControlWrapper';

import { tools } from '@cqsjjb/jjb-common-lib';
import { Connect } from '@cqsjjb/jjb-dva-runtime';
import { AntdTableFuncControl } from '@cqsjjb/jjb-common-decorator/antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Checkbox,
  Empty,
  Flex,
  Form,
  Input,
  message,
  Modal,
  Pagination,
  Radio,
  Select,
  Space,
  Spin,
  Splitter,
  Table,
  TreeSelect
} from 'antd';

import { NS_QUESTION_BANK_MANAGE, NS_GLOBAL } from '~/enumerate/namespace';

import { InjectContext } from '~/enumerate/context';

import SetClassifyModal from '../components/SetClassifyModal';
import QuestionBankModal from '../components/QuestionBankModal';
import SetQuestionBankModal from '../components/SetQuestionBankModal';

import './index.less';
// 题库管理
const List = AntdTableFuncControl(props => {
  const context = React.useContext(InjectContext);
  // 从props中解构questionBankManage和global命名空间的数据
  const {
    questionBankManage: { loading, questionBankList, questionBankTotal, classifyList, classifyTotal },
    global
  } = props;

  // 从global命名空间获取getPostTreeAction
  const getPostTreeAction = props.getPostTreeAction || global?.getPostTreeAction;
  const [form] = Form.useForm();
  const [state, setState] = React.useState({
    currentData: null,
    showClassifyModal: false, // 分类弹窗控制
    isEdit: false, // 是否是编辑分类
    showQuestionBankModal: false, // 题库弹窗控制
    currentQuestionBankId: null, // 当前题库ID
    treeData: [] // 岗位树数据
  });

  const [questionBankState, setQuestionBankState] = React.useState({
    showModal: false,
    currentData: null,
    isEdit: false,
    selectedClassifyId: null
  });

  // 获取岗位树数据
  const getPostTreeData = () => {
    // 使用我们从props或global中获取的action
    if (getPostTreeAction) {
      getPostTreeAction().then(resp => {
        console.log('岗位树数据:', resp);
        if (resp.success && resp.data && Array.isArray(resp.data)) {
          setState(prev => ({
            ...prev,
            treeData: resp.data
          }));
        }
      }).catch(error => {
        console.error('获取岗位树数据失败:', error);
      });
    } else {
      console.warn('getPostTreeAction未定义');
    }
  };

  // 处理树形结构数据，保持所有节点可选
  const dealTreeParentDisabledStyle = (data, childrenKey = 'children') => {
    if (!data || !Array.isArray(data)) {
      console.warn('树形数据格式错误或为空');
      return [];
    }
    console.warn(data, '树形数据格式错误或为空');
    return data;
    // 只进行深拷贝，不设置任何节点为不可选
    const newData = JSON.parse(JSON.stringify(data));
    console.log(newData);
    return newData;
  };

  // 选择岗位类型
  const onSelectType = (value) => {
    form.setFieldsValue({ parentPostId: value });
  };

  const [selectedClassify, setSelectedClassify] = React.useState(null);

  const [selectRows, setSelectRows] = React.useState([]);

  const getClassifyList = () => {
    props.getQuestionBankClassifyListAction({
      pageIndex: 1,
      pageSize: 100 // 获取足够多的分类
    });
  };

  const getList = params => {
    tools
      .routerParamMerge({
        ...tools.routerParamQuery(),
        ...params,
      })
      .then(() => props.getQuestionBankListAction(tools.routerParamQuery()));
  };

  const deleteById = ids => {
    Modal.confirm({
      title: '提示',
      content: '是否确认删除?',
      onOk: () => batchDeleteQuestionBank(ids)
    });
  };

  const allSelect = checked => {
    if (checked) {
      setSelectRows(questionBankList);
    } else {
      setSelectRows([]);
    }
  };

  const pageObj = {
    total: questionBankTotal,
    showQuickJumper: true,
    showSizeChanger: true,
    showTotal: total => `共${total}条数据`,
    current: parseInt(tools.routerParamQuery().pageIndex || 1),
    pageSize: parseInt(tools.routerParamQuery().pageSize || 10),
    onChange: (pageIndex, pageSize) => {
      getList({
        pageIndex,
        pageSize
      });
      setSelectRows([]);
    }
  };

  const batchDeleteQuestionBank = ids => {
    props.deleteQuestionBankAction(ids).then(resp => {
      if (resp.success) {
        getList();
        context.message.success('删除成功');
      }
    });
  };

  const copyQuestionBank = id => {
    props.copyQuestionBankAction({ id }).then(res => {
      if (res.success) {
        message.success('复制成功');
        getList();
      }
    });
  };

  const columns = [
    {
      title: '题库编码',
      dataIndex: 'id',
      key: 'code',
      render: (text) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img src="" alt="" style={{ marginRight: '5px' }} />
          {text}
        </div>
      )
    },
    {
      title: '题库封面',
      dataIndex: 'questionBankCoverUrl',
      key: 'questionBankCoverUrl',
      render: (text) => (
        text ? <img src={text} alt="题库封面" style={{ width: '50px', height: '50px' }} /> : null
      )
    },
    {
      title: '题库名称',
      dataIndex: 'questionBankName',
      key: 'questionBankName',
    },
    {
      title: '题库分类',
      dataIndex: 'classifyName',
      key: 'classifyName',
    },
    {
      title: '岗位',
      dataIndex: 'postName',
      key: 'postName',
    },
    {
      title: '习题数量',
      dataIndex: 'questionNum',
      key: 'questionNum',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
  ];

  React.useEffect(() => {
    getClassifyList();
    getPostTreeData(); // 获取岗位树数据
    const urlParams = tools.routerParamQuery();
    const classifyId = urlParams.classifyId || null;
    setSelectedClassify(classifyId);
    getList({
      pageIndex: urlParams.pageIndex || 1,
      pageSize: urlParams.pageSize || 10,
      classifyId
    });
  }, []);

  return (
    <PageLayout
      title="题库管理"
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setQuestionBankState({
              showModal: true,
              currentData: null,
              isEdit: false,
              selectedClassifyId: selectedClassify
            });
          }}
        >
          新增
        </Button>
      }
    >
      <div className="question-bank-container">
        <Splitter style={{ height: '100%' }}>
          <Splitter.Panel defaultSize='18%' className="question-bank-category">
            <Flex justify="space-between">
              <div className="category-title">题库分类</div>
              <Button
                type='primary'
                size='small'
                onClick={() => {
                  setState({
                    currentData: null,
                    showClassifyModal: true,
                    isEdit: false
                  });
                }}
              >
                添加分类
              </Button>
            </Flex>
            <div className="classify-radio-group">
              {classifyList && classifyList.length > 0 ? (
                <Radio.Group
                  value={selectedClassify}
                  onChange={(e) => {
                    setSelectedClassify(e.target.value);
                    getList({ classifyId: e.target.value, pageIndex: 1 });
                  }}
                >
                  <Radio value={null} style={{ display: 'block', marginBottom: '8px' }}>全部</Radio>
                  {classifyList.map(item => (
                    <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                      <Radio
                        value={item.id}
                        style={{ display: 'block' }}
                      >
                        {item.classifyName}
                      </Radio>
                      {/* <Space>
                        <Button
                          type="link"
                          size="small"
                          onClick={(e) => {
                            e.stopPropagation();
                            setState({
                              currentData: item,
                              showClassifyModal: true,
                              isEdit: true
                            });
                          }}
                        >
                          编辑
                        </Button>
                        <Button
                          type="link"
                          danger
                          size="small"
                          onClick={(e) => {
                            e.stopPropagation();
                            Modal.confirm({
                              title: '提示',
                              content: '确定要删除该分类吗？',
                              onOk: () => {
                                props.deleteClassifyAction({ id: item.id }).then(resp => {
                                  if (resp.success) {
                                    context.message.success('删除成功');
                                    getClassifyList();
                                    if (selectedClassify === item.id) {
                                      setSelectedClassify(null);
                                      getList({ classifyId: null, pageIndex: 1 });
                                    }
                                  }
                                });
                              }
                            });
                          }}
                        >
                          删除
                        </Button>
                      </Space> */}
                    </div>
                  ))}
                </Radio.Group>
              ) : (
                <Empty description="暂无分类数据" />
              )}

              {/* 新增/编辑题库弹窗 */}
              {questionBankState.showModal && (
                <SetQuestionBankModal
                  close={(refresh) => {
                    setQuestionBankState({
                      ...questionBankState,
                      showModal: false,
                      currentData: null,
                      isEdit: false
                    });
                    if (refresh) {
                      getList({ classifyId: selectedClassify });
                    }
                  }}
                  currentData={questionBankState.currentData}
                  isEdit={questionBankState.isEdit}
                  selectedClassifyId={questionBankState.selectedClassifyId}
                  treeData={state.treeData}
                />
              )}
            </div>
          </Splitter.Panel>
          <Splitter.Panel>
            <div className="question-bank-table-container">
              <div className="category-title">{selectedClassify ? classifyList.find(item => item.id === selectedClassify)?.classifyName : '全部'}</div>
              <SearchForm
                form={form}
                loading={loading}
                formLine={[
                  <Form.Item
                    noStyle
                    name="questionBankName"
                  >
                    <Input
                      allowClear
                      placeholder="请输入名称"
                    />
                  </Form.Item>,
                  <Form.Item
                    noStyle
                    name="parentPostId"
                    label="选择岗位"
                  >
                    <TreeSelect
                      // showSearch
                      placeholder='请选择岗位'
                      style={{ width: '100%' }}
                      fieldNames={
                        {
                          label: 'postName',
                          value: 'id',
                          children: 'children'
                        }
                      }
                      onSelect={onSelectType}
                      treeData={dealTreeParentDisabledStyle(state.treeData)}
                      allowClear
                    // treeDefaultExpandAll
                    />
                  </Form.Item>
                ]}
                onReset={() =>
                  getList({
                    questionBankName: '',
                    parentPostId: ''
                  })
                }
                onFinish={values => getList(values)}
              />
              <div className="question-bank-table">
                <div className="all-action-btn">
                  <div className="left">
                    <Checkbox
                      checked={
                        selectRows.length === questionBankList.length &&
                        questionBankList.length !== 0
                      }
                      onChange={e => allSelect(e.target.checked)}
                    >
                      全选
                    </Checkbox>
                    <div>已勾选 {selectRows.length} 个题库</div>
                  </div>
                  {/* <div className="right">
                    <Space>
                      <Button
                        ghost
                        danger
                        icon={<DeleteOutlined />}
                        disabled={selectRows.length === 0}
                        onClick={() => deleteById(selectRows.map(v => v.id))}
                      >
                        删除
                      </Button>
                    </Space>
                  </div> */}
                </div>
                <Spin spinning={loading}>
                  <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={questionBankList}
                    pagination={false}
                    rowSelection={{
                      selectedRowKeys: selectRows.map(item => item.id),
                      onSelect: (record, selected) => {
                        if (selected) {
                          setSelectRows([...selectRows, record]);
                        } else {
                          setSelectRows(selectRows.filter(item => item.id !== record.id));
                        }
                      },
                      onSelectAll: selected => {
                        if (selected) {
                          setSelectRows(questionBankList);
                        } else {
                          setSelectRows([]);
                        }
                      }
                    }}
                  />
                </Spin>
                <div
                  style={{
                    display: 'flex',
                    padding: '10px 0',
                    backgroundColor: '#fff',
                    justifyContent: 'flex-end'
                  }}
                >
                  <Pagination {...pageObj} />
                </div>
              </div>
            </div>
          </Splitter.Panel>
        </Splitter>
      </div>
      {state.showClassifyModal && (
        <SetClassifyModal
          close={(refresh) => {
            setState(prev => ({
              ...prev,
              currentData: null,
              showClassifyModal: false,
              isEdit: false
            }));
            if (refresh) {
              getClassifyList();
            }
          }}
          currentData={state.currentData}
          isEdit={state.isEdit}
        />
      )}

      {/* 题库弹窗 */}
      {state.showQuestionBankModal && (
        <QuestionBankModal
          visible={state.showQuestionBankModal}
          questionBankId={state.currentQuestionBankId}
          onCancel={() => {
            setState(prev => ({
              ...prev,
              showQuestionBankModal: false,
              currentQuestionBankId: null
            }));
          }}
          {...props}
        />
      )}
    </PageLayout>
  );
});
export default Connect([NS_QUESTION_BANK_MANAGE, NS_GLOBAL], true)(List);